<template>
	<view class="order-detail" :style="css.page+'min-height:'+$xyfun.xysys().windowHeight+'px'" v-if="!isEmpty">
		<view class="top psr" :style="css.mcbg">
			<image class="bg" src="/static/images/status-bg.png" mode="widthFix" />
			<view class="status-left flex">
				<image :src="'/static/images/order-status'+order.status+'.png'" mode="widthFix"
					v-if="order.status >=0" />
				<image src="/static/images/order-status-close.png" mode="widthFix" v-else />
				<view class="status-box m-l-20 tc-w">
					<view :class="'name tb ts-34 ' + (order.status == -2 ? 'p-t-10':'p-t-40')">
						{{order.status_text}}
					</view>
					<view class="tips ts-28 lh-28 m-t-10 tc-w" v-if="order.status == -2">长时间未支付，订单自动关闭</view>
				</view>
			</view>
			<view class="status-right ts-28 tc-w" v-if="order.status ==0">
				<view class="flex">
					<text>剩余时间：</text>
					<view class="time">{{time}}</view>
				</view>
			</view>
		</view>

		<view v-if="type == 'order'" class="flex p-lr-30 m-30 br-10 bc-w">
			<view class="item-list flex ">
				<view v-for="(g,index) in order.item" :key="index" :style="css.blpc"
					:class="'item p-tb-30 flex '+(index == order.item.length-1?'':'bl-b')">
					<view class="l ovh br-10">
						<image :src="order.storelogo" mode="widthFix" />
					</view>
					<view class="r psr m-l-20">
						<view class="tb lh-40 goods-title">
							{{order.storename}}
						</view>
						<view class="venue m-t-10">
							{{order.venuename}} - {{g.area}}
						</view>
						<view class="date m-t-20 ts-26" :style="css.tcl">
							{{g.date}} {{g.week}} {{g.starttime}}-{{g.endtime}}
						</view>
						<view class="price-box flex psa lh-32">
							<text :style="css.tcp">￥</text>
							<text :style="css.tcp" class="ts-32 tb">{{ g.price }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="m-t-30 br-10 m-lr-30 m-b-30 p-30 bc-w">
			<view class="flex">
				<text>订单编号：</text>
				<text>{{order.order_sn}}</text>
				<text @tap="$xyfun.copy(order.order_sn)" class="ts-24 bl br-10 m-l-25 p-lr-10"
					:style="css.pbg">复制</text>
			</view>
			<view class="flex m-t-20">
				<text>下单时间：</text>
				<text>{{$xyfun.timeFormat(order.createtime)}}</text>
			</view>
		</view>
		<view class="m-t-30 br-10 m-lr-30 m-b-30 p-30 bc-w">

			<view class="flex">
				<text>订单金额：</text>
				<view class="m-l-auto tb"><text>¥</text>{{order.total_amount}}</view>
			</view>

			<view class="flex m-t-20">
				<text>优惠金额：</text>
				<view class="m-l-auto tb"><text>¥</text>{{order.coupon_fee}}</view>
			</view>
			<view class="flex m-t-20">
				<text>需付金额：</text>
				<view class="m-l-auto tb"><text>¥</text>{{order.total_fee}}</view>
			</view>

			<view class="flex m-t-20">
				<view class="m-l-auto tb lh-34">
					<text>实付金额：</text>
					<text :style="css.tcp">¥</text>
					<!-- <text class="ts-34" :style="css.tcp">{{order. ? order.pay_fee : order.total_fee}}</text> -->
					<text class="ts-34" :style="css.tcp">{{ order.total_fee}}</text>
				</view>
			</view>
		</view>
		<view class="bottom-fixed flex tc bc-w" v-if="order.status == 0">
			<view class="p-lr-30 p-tb-15 flex tc wa">
				<view class="action flex m-l-auto">
					<view class="close m-r-40" :style="css.pbg+css.tcl" @tap="closeOrder()">取消订单</view>
					<view class="pay m-l-auto tc-w" :style="css.mcbg" @tap="onPay()">支付</view>
				</view>
			</view>
		</view>

		<view class="bottom-fixed flex tc bc-w" v-if="type == 'order' && order.status == 1">
			<view class="p-lr-30 p-tb-15 flex tc wa">
				<view class="action flex m-l-auto">
					<view class="close" :style="css.pbg+css.tcl" @tap="refund(order.id)">退订</view>
				</view>
			</view>
		</view>

		<!--支付弹窗-->
		<block v-if="payModelShow">
			<view class="xy-modal-box xy-modal-box-center pay-model-box p-t-30 br-10 bc-w"
				:class="[payModelShow?'xy-modal-show':'']">
				<view class="title m-b-50 ts-32 tc bl-b p-b-30" :style="css.blpc">支付方式</view>
				<view class="tc tb m-tb-40 ts-36">支付金额{{ order.total_fee || "0.00" }}元</view>
				<view class="pay-list">
					<view class="item flex p-30 m-b-2 lh-40 bc-w" v-for="(item, index) in payList" :key="index"
						v-if="item.state">
						<view class="l flex">
							<text :class="'xyicon icon-'+item.icon+' ts-40 m-r-15'"></text>
							<text class="lh-40">{{item.name}}</text>
						</view>
						<view class="r tb m-l-auto" @tap="payMethodSelect(index)">
							<text class="xyicon icon-radio-a ts-32 lh-40" v-if="item.select"></text>
							<text class="xyicon icon-radio ts-32 lh-40" v-else></text>
						</view>
					</view>
				</view>

				<button :style="css.mcbg" class="ts-30 lh-30 p-25 tc-w m-30" @tap="subPay()">确认支付</button>
			</view>
			<view class="xy-modal-mask" :class="[payModelShow?'xy-mask-show':'']" @tap="payModelShow =!payModelShow">
			</view>
		</block>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import Pay from '@/utils/pay';

	export default {
		data() {
			return {
				css: {},
				isEmpty: true,
				id: 93,
				type: 'goods',
				order: {},
				time: '',
				timer: null,
				payModelShow: false,
				disabled: false,
				payList: [{
						name: '余额支付',
						method: 'balance',
						icon: 'balance',
						state: true,
						select: false
					},
					{
						name: '微信支付',
						method: 'wechat',
						icon: 'wechat',
						state: true,
						select: true
					}
				]
			}
		},
		computed: {
			...mapState(['common', 'user'])
		},
		async onLoad() {
			var options = this.$Route.query;
			if (options) {
				this.id = options.id;
				this.type = options.type;
			}
			this.$xyfun.setNavBg();
			this.css = this.$xyfun.css();
			this.loadData();
		},
		methods: {

			async loadData() {
				var url = '';
				switch (this.type) {
					case 'order':
						url = '/order/detail';
						break;
					default:
						break;
				}
				if (url != '') {
					this.$api.post({
						url: url,
						loadingTip: '加载中...',
						data: {
							id: this.id,
						},
						success: res => {
							this.isEmpty = false;
							this.order = res;
							if (res.status == 0) {
								this.timer = setInterval(() => {
									this.countDown(res.ext_arr.expired_time);
								}, 1000)
							}
						}
					});
				}
			},

			//倒计时
			countDown(endtime) {
				const remainingTime = this.$xyfun.intervalTime(endtime);
				this.time = remainingTime;

				// 当剩余时间为 '00:00:00' 时，取消订单
				if (remainingTime === '00:00:00') {
					clearInterval(this.timer); // 停止计时器
					this.closeOrder(); // 调用取消订单的方法
				}
			},

			//退订
			refund(id) {
				var that = this;

				// 获取订单的开始时间（拼接日期和开始时间）
				var orderStartDateTime = new Date(this.order.date + ' ' + this.order.item[0].starttime).getTime(); // 转为时间戳

				// 获取当前时间
				var currentTime = new Date().getTime();

				// 判断当前时间是否已经超过订单开始时间
				if (currentTime >= orderStartDateTime) {
					that.$xyfun.msg('当前时间已超过订单开始时间，无法退订');
					return; // 如果当前时间大于订单开始时间，则禁止退订
				}
				uni.showModal({
					title: '提示',
					content: '确定要退订吗？',
					success(e) {
						if (e.confirm) {
							that.$xyfun.storeId().then((store_id) => {
								console.log(store_id)
								that.$api.post({
									url: '/shande/refund',
									data: {
										id: id,
										store_id: store_id,
									},
									success: res => {
										that.$xyfun.msg('退订成功')
										that.order.status = -3;
										that.order.status_text = '已退订'
									}
								});
							})
						}
					}
				})
			},

			//关闭订单
			closeOrder() {
				var url = '';
				switch (this.type) {
					case 'order':
						url = '/order/cancel'
						break;
					default:
						break;
				}
				if (url != '') {
					this.$api.post({
						url: url,
						data: {
							id: this.id,
						},
						success: res => {
							this.loadData();
						}
					});
				}
			},

			// 重新支付
			onPay() {
				this.payModelShow = true;
			},

			//支付方式选择
			payMethodSelect(key) {

				this.payList.map((value, index) => {
					if (index == key) {
						value.select = !value.select;
					} else {
						value.select = false;
					}
				});
			},

			//确认支付
			subPay() {
				if (this.disabled) {
					return false;
				}
				this.disabled = true;

				var pay_type = '';
				this.payList.map((value) => {
					if (value.select) {
						pay_type = value.method;
					}
				});
				if (!pay_type) {
					this.$xyfun.msg('请选择支付方式');
				} else {
					// 支付订单
					if (pay_type == 'wechat') {
						//发起支付
						console.log(this.order)
						this.$xyfun.storeId().then((store_id) => {
							this.$api.post({
								url: '/Shande/test',
								data: {
									orderjson: this.order
								},
								success: res => {
									const jsonData = JSON.parse(res.data);
									const payDataString = jsonData.pay_data; // 获取 pay_data 的 JSON 字符串
									const payData = JSON.parse(payDataString); // 解析成对象
									return new Promise((resolve, reject) => {
										uni.requestPayment({
											appId: payData.appId,
											nonceStr: payData.nonceStr,
											package: payData.package,
											paySign: payData.paySign,
											signType: payData.signType,
											timeStamp: payData.timeStamp,
											success: (e) => {
												this.payResult("success");
											},
											fail: (e) => {
												uni.showModal({
													content: "支付失败,原因为: " +
														e.errMsg,
													showCancel: false
												})
											}
										})
									});
								}
							});
						})
					} else {
						this.$xyfun.storeId().then((store_id) => {
							this.$api.post({
								url: '/pay/prepay',
								data: {
									order_sn: this.order.order_sn,
									payment: 'balance',
									order_type: 'order',
									user_id: uni.getStorageSync('xyvenue:user').id,
									store_id: store_id,
									amount: this.order.total_fee
								},
								success: res => {
									uni.navigateTo({
										url: `/pages/user/order/payresult?orderId=${this.order.id}&type=balance&payment=balance&payState=success&orderType=order`
									})
								},
								fail: res => {
									console.log(res);
									this.disabled = false;
								}
							});
						})
					}
				}
			},

		}
	}
</script>

<style scoped lang="scss">
	.order-detail {
		padding-bottom: 150rpx;

		.top {
			.bg {
				width: 750rpx;
			}

			.status-left {
				position: absolute;
				left: 50rpx;
				top: 40rpx;

				image {
					width: 120rpx;
				}
			}

			.status-right {
				position: absolute;
				right: 30rpx;
				top: 80rpx;
			}
		}

		.time {
			width: 115rpx;
		}

		.bottom-fixed {
			.close {
				width: 220rpx;
				height: 74rpx;
				border-radius: 37rpx;
				line-height: 74rpx;
			}

			.pay {
				width: 180rpx;
				height: 74rpx;
				border-radius: 37rpx;
				line-height: 74rpx;
			}
		}

		.logistics-model-box {
			width: 660rpx;
		}

		.pay-model-box {
			width: 80%;
		}

	}

	.item-list {
		.item {
			.l {
				width: 150rpx;
				height: 150rpx;

				image {
					width: 150rpx;
					height: 150rpx;
				}
			}

			.r {
				width: 460rpx;

				.price-box {
					position: absolute;
					right: 0;
					top: 0;
				}
			}
		}
	}
</style>